<template>
  <div>
    <el-row>
      <el-col :span="24" align="right">
        <el-button type="primary" @click="addPeople()">添加</el-button>
      </el-col>
    </el-row>
    <Table :tableArr="membersList" :pagination="data.page" :columns="data.columns">
      <template #operate="{ row }">
        <el-button size="small" type="danger" @click="handleEdit(row)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
      </template>
    </Table>

    <el-dialog v-model="data.addPeople" append-to-body width="50%" :show-close="false" @closed="close"
      :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="data.activeName" class="demo-tabs">
            <el-tab-pane label="添加人员" name="first">
              <el-form :model="form" label-position="left" label-width="90px" :inline="true" class="demo-form-inline">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="单位类型：" required label-width="110">

                      <SelectOption :selectValue="form.unitType" :options="data.unitSelet" @change-value="changeValue0"></SelectOption>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="单位名称："  required label-width="110">
                      <popup-tree-input v-if="form.unitType == '0'"
                          :data="data.popupTreeData"
                          :props="data.popupTreeProps"
                          :prop="
                              data.deptForm.parentName == null
                              ? $t('message.org.top_menu')
                              : form.memberName
                            "
                          :node-key="'' + data.deptForm.parentId"
                          :current-change-handle="changeValue7"
                          />
                      <el-input type="text" v-model="form.memberName" @change="form.memberId = form.memberName" v-else maxlength="30" show-word-limit clearable></el-input>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="排名：" required>
<!--                      <el-input type="number" v-model="form.sort"  :min="1" :max="9999" controls ></el-input>-->
                      <el-input  v-model="form.sort"   :min="1" oninput="value=value.replace(/[^0-9]/g, '')"  maxlength="5"  ></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系人：" required>
                      <el-input type="text" v-model="form.contactPersonId" v-if="form.unitType == '1'" @change="form.contactPerson= form.contactPersonId" maxlength="30" show-word-limit clearable ></el-input>
                      <!-- <SelectOption :selectValue="form.contactPerson"  :options="data.roleList" @change-value="changeValue2" v-else ></SelectOption> -->
                      <user-list-modal
                          v-model="form.contactPerson"
                          @update:modelValue="changeValue2"
                          :default-users="[]"
                          :multiple="false"
                          :orgid="data.userOrgId"
                          :noOrgTip="form.memberId==''"
                          :devType="'platform'"
                          v-else
                        />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系方式：">
                      <el-input type="text" v-model="form.contactPhone" :disabled="form.unitType == '0'" maxlength="30" show-word-limit clearable></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">关闭</el-button>
          <el-button type="primary" @click="save()">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import * as proxy from '@/constants/proxy'
import request from '@/utils/request'
import { validatePhoneNumber } from '@/utils/util'
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import common from '@/views/science/common/common.json'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { tips } from '@/views/science/components/tips/tips'
import { onMounted, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'


export default {
  components: {
    Table,
    SelectOption,
    PopupTreeInput,
    UserListModal
  },
  emits: {
    dataChange: null,
    paramsChange: null,
  },
  props: {
    members: {
      type: Array,
      required: true,
    },
    membersFlag: {
      type: Boolean,
      required: true,
    }
  },
  setup(props, { emit }) {
    const store = useStore()
    const value = ref([])
    let data = reactive({
      activeName: ref('first'),
      columns: common.platformUnitHeader,
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      addPeople: false,
      // unitSelet: computed(() => store.state.technologyStrength.unitSelet),
      unitSelet: [{id:'0',name:'内部公司'},{id:'1',name:'外部公司'}],
      // usersSelet: computed(() => store.state.technologyStrength.usersSelet),
      usersSelet: [],
      // roleList: computed(() => store.state.technologyStrength.ptRoleList),
      roleList:[],
      //----------------------
      popupTreeData: [],//单位名称
      popupTreeProps: {//单位名称
        label: 'name',
        children: 'children',
      },
      deptForm : {
          parentId: 0,
          parentName: '',
        },
      addType:'add',//add or edit
      editItem:{},//当前编辑的人员
      userOrgId:''
    })
    const membersList = reactive([] as any)
    const form = reactive({
      unitName:'',
      unitType: '',//单位类型
      memberName:'',//单位名称
      memberId: "",//单位名称
      sort: 1,//排名
      contactPerson:'',//联系人
      contactPersonId:'',//联系人
      contactPhone:'',//联系方式
      id:new Date().getTime(),
    }) as any

    // 字典
    const affiliation = async () => {
      // request({
      //   url: proxy.CHECC_API_CMS + '/dictItem/codelist',
      //   method: 'post',
      //   data:["KJSL_STANDARD_LEVEL_CATEGORY","KJSL_PREPARATION_CATEGORY","KJSL_AT_PRESENT_STAGE","KJSL_PARTICIPATION_STATUS1","KJSL_BUSINESS_SECTOR","KJSL_STANDARD_LEVEL_CATEGORY"]
      // }).then((res) => {
      // })

      return request({
                url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
                method: "get",
            }).then(res => {
                data.popupTreeData = res.data.data
            })
      // request({
      //   url: proxy.CHECC_API_CMS + '/user/getAll',
      //   method: 'get',
      // }).then((res) => {
      //   data.roleList = res.data.data
      // })
      // let res = await  getOrgTree()
      // data.popupTreeData = res.data.data
    }

    const changeValue7 = (item) => {
      console.log('changeValue7');  
      data.userOrgId = item.id;
      form.memberName = item.name
      form.memberId = item.id
    }

    const changeValue0 = (item) => {
      form.unitType = item.id
      form.unitName = item.name
      form.memberName =''
      form.memberName =[]
      form.memberId =''
      form.memberId =[]
      form.contactPerson =''
      form.contactPerson =[]
      form.contactPersonId =''
      form.contactPersonId =[]
      // const params = {
      //   currentPage: 1,
      //   isPage: 0,
      //   orgIds: [item.id],
      //   size: 10000,
      //   type: 0
      // }
    }
    //联系人
    const changeValue2 = (item) => {
      form.contactPersonId = item.userId
      form.contactPerson = item.cname
      if(form.unitType == '0'){
        form.contactPhone = item.phone
      }else{
        form.contactPhone = ''
      }
    }
    //添加人员
    const addPeople = () => {
      data.addPeople = true
      data.addType = 'add'
    }
    //编辑人员
    const handleEdit =(row)=>{
      console.log('编辑',row);
      // form = row
      Object.assign(form,row)
      data.addPeople = true
      data.addType = 'edit'
      data.editItem = row
    }
    //保存
    const save = async () => {
      if(form.contactPersonId == '' || form.memberId == '' ){
        tips("请将人员信息填写完整", "warning");
        return
      }
      if (form.contactPhone && !validatePhoneNumber(form.contactPhone)) {
        tips("联系电话格式不正确！", 'warning');
        return false;
      }

      if(data.addType == 'add'){
        form.unitName = (form.unitType == '0' ? '内部公司' : '外部公司')

       membersList.push(JSON.parse(JSON.stringify(form)))
      }else{
        var index = membersList.indexOf(data.editItem);
        if (index > -1) {//大于0 代表存在，
          membersList[index] = JSON.parse(JSON.stringify(form))
        }
      }
      emit('paramsChange', membersList)
      close()
    }
    const close = () =>{
      data.addPeople = false
      form.unitName = ''
      form.unitType = '0'
      form.memberName = ''
      form.memberId = ''
      form.sort = 1
      form.contactPerson = ''
      form.contactPersonId = ''
      form.contactPhone = ''
      form.id = new Date().getTime()
    }

    //删除
    const handleDelete = async (row) => {
      var index = membersList.indexOf(row);
      if (index > -1) {//大于0 代表存在，
        membersList.splice(index, 1);//存在就删除
      }
      emit('paramsChange', membersList)
    }

    onMounted(()=>{
      affiliation()
    })

    watch(() => props.members, (newValue, oldValue) => {
      //  membersList = -
      if(!props.membersFlag){
        return
      }
      membersList.length = 0
      if(newValue.length >0){
        newValue.forEach(e =>{

          membersList.push(e)
        })
      }
      membersList.forEach(e =>{
        e.unitName  =  e.unitType == '0' ? '内部公司' : '外部公司'
      })
       console.log('watch  props.members',newValue);
    })

    return {
      data,
      form,
      value,
      membersList,
      handleEdit,
      addPeople,
      close,
      handleDelete,
      save,
      changeValue0,
      changeValue2,
      changeValue7,
      affiliation
    }
  },
}
</script>

<style scoped lang="scss">
.demo-form-inline .el-form-item {
  width: 70%;
}

.el-select {
  width: 100%;
  margin: 0;
}
</style>
